package com.itcam.otcbackend.demo;

/**
 * @author : Cammy.Wu
 * Description : 
 */

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {2,1,4,3,7,6,5};
        quickSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    public static void quickSort(int[] a) {
        quick(a, 0, a.length - 1);
    }

    public static void quick(int[] a, int left, int right) {
        if (left >= right) {
            return;
        }
        int p = partition(a, left, right); // p代表基准点元素索引}
        quick(a, left, p - 1);
        quick(a, p + 1, right);

    }

    private static int partition(int[] a, int left, int right) {
        int pv = a[right]; // 基准点元素的值
        int i = left;
        int j = left;
        while (j < right) {
            if (a[j] < pv) { // 找到比基准点小的
                if (i != j) {
                    swap(a, i, j);
                }
                // 没找到大的
                i++;
            }
            j++;
        }
        swap(a, i, right);
        return i;
    }

    private static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
